<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('page.system.userMembership.renew')"
    width="500px"
    :before-close="handleClose"
  >
    <div v-if="membershipData" class="renew-form">
      <!-- 当前会员信息 -->
      <el-card class="current-info" shadow="never">
        <template #header>
          <span>当前会员信息</span>
        </template>
        <el-descriptions :column="1" size="small">
          <el-descriptions-item :label="$t('page.system.userMembership.nickName')">
            {{ membershipData.nickName }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.system.userMembership.levelName')">
            <el-tag :type="getLevelTagType(membershipData.levelCode || '') as any">
              {{ membershipData.levelName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.system.userMembership.endDate')">
            {{ formatDateTime(membershipData.endDate || '') }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.system.userMembership.remainingDays')">
            <el-tag :type="getRemainingDaysTagType(membershipData.remainingDays || 0)">
              {{ membershipData.remainingDays }}天
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 续费表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="margin-top: 20px"
      >
        <el-form-item :label="$t('page.system.userMembership.periodType')" prop="periodType">
          <el-select
            v-model="form.periodType"
            :placeholder="$t('page.system.userMembership.form.periodTypeRequired')"
            style="width: 100%"
            @change="handlePeriodTypeChange"
          >
            <el-option
              v-for="period in periodTypes"
              :key="period.value"
              :label="period.label"
              :value="period.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('page.system.userMembership.periodValue')" prop="periodValue">
          <el-input-number
            v-model="form.periodValue"
            :placeholder="$t('page.system.userMembership.form.periodValueRequired')"
            :min="1"
            :max="99"
            style="width: 100%"
            @change="calculateNewEndDate"
          />
        </el-form-item>

        <el-form-item label="续费后到期时间">
          <el-input
            :value="newEndDate"
            readonly
            placeholder="请选择续费周期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="续费费用">
          <div class="renewal-cost">
            <el-tag type="danger" size="large">¥{{ calculateCost() }}</el-tag>
            <span class="cost-note">（估算费用，实际以支付为准）</span>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ $t('page.system.userMembership.cancel') }}</el-button>
        <el-button 
          type="primary" 
          :loading="loading" 
          :disabled="!newEndDate"
          @click="handleSubmit"
        >
          {{ $t('page.system.userMembership.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import {
  ElButton,
  ElCard,
  ElDescriptions,
  ElDescriptionsItem,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElOption,
  ElSelect,
  ElTag,
  type FormInstance,
  type FormRules,
} from 'element-plus';

import type { RenewParams, UserMembership } from '#/api/system/user-membership';
import { renewUserMembershipApi } from '#/api/system/user-membership';
import { $t } from '#/locales';

interface Props {
  visible: boolean;
  membershipData?: Partial<UserMembership>;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'submit'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const loading = ref(false);
const newEndDate = ref('');

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

// 周期类型选项
const periodTypes = [
  { value: 1, label: '天卡' },
  { value: 2, label: '周卡' },
  { value: 3, label: '月卡' },
  { value: 4, label: '季卡' },
  { value: 5, label: '年卡' },
];

// 续费表单
const form = reactive<Omit<RenewParams, 'id'>>({
  periodType: 3,
  periodValue: 1,
});

const rules: FormRules = {
  periodType: [
    { required: true, message: $t('page.system.userMembership.form.periodTypeRequired'), trigger: 'change' },
  ],
  periodValue: [
    { required: true, message: $t('page.system.userMembership.form.periodValueRequired'), trigger: 'blur' },
    { type: 'number', min: 1, message: $t('page.system.userMembership.form.periodValueMin'), trigger: 'blur' },
  ],
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN');
};

// 获取等级标签类型
const getLevelTagType = (levelCode: string) => {
  const colorMap: { [key: string]: string } = {
    'DUKE': 'danger',     // 公
    'MARQUIS': 'warning', // 侯
    'EARL': 'primary',    // 伯
    'FREE': 'success',    // 民
  };
  return colorMap[levelCode] || 'info';
};

// 获取剩余天数标签类型
const getRemainingDaysTagType = (days: number) => {
  if (days <= 0) return 'danger';    // 已过期
  if (days <= 7) return 'warning';   // 即将过期
  if (days <= 30) return 'primary';  // 一个月内
  return 'success';                  // 充足
};

// 计算新的到期时间
const calculateNewEndDate = () => {
  if (!props.membershipData?.endDate || !form.periodType || !form.periodValue) {
    newEndDate.value = '';
    return;
  }

  const currentEndDate = new Date(props.membershipData.endDate);
  const newDate = new Date(currentEndDate);

  switch (form.periodType) {
    case 1: // 天卡
      newDate.setDate(newDate.getDate() + form.periodValue);
      break;
    case 2: // 周卡
      newDate.setDate(newDate.getDate() + form.periodValue * 7);
      break;
    case 3: // 月卡
      newDate.setMonth(newDate.getMonth() + form.periodValue);
      break;
    case 4: // 季卡
      newDate.setMonth(newDate.getMonth() + form.periodValue * 3);
      break;
    case 5: // 年卡
      newDate.setFullYear(newDate.getFullYear() + form.periodValue);
      break;
  }

  newEndDate.value = newDate.toLocaleString('zh-CN');
};

// 计算续费费用
const calculateCost = () => {
  if (!form.periodType || !form.periodValue) return 0;

  // 根据等级和周期类型计算费用（这里使用模拟数据）
  const basePrices: { [key: number]: number } = {
    1: 10,   // 天卡基础价格
    2: 60,   // 周卡基础价格
    3: 199,  // 月卡基础价格
    4: 399,  // 季卡基础价格
    5: 1299, // 年卡基础价格
  };

  const levelMultipliers: { [key: string]: number } = {
    'DUKE': 1.0,      // 公爵
    'MARQUIS': 0.8,   // 侯爵
    'EARL': 0.6,      // 伯爵
    'FREE': 0,        // 免费
  };

  const basePrice = basePrices[form.periodType] || 0;
  const levelCode = props.membershipData?.levelCode || 'FREE';
  const multiplier = levelMultipliers[levelCode] || 0.6;

  return Math.round(basePrice * form.periodValue * multiplier);
};

// 周期类型变化
const handlePeriodTypeChange = () => {
  // 根据周期类型设置默认数量
  if (form.periodType === 1) { // 天卡
    form.periodValue = 30;
  } else {
    form.periodValue = 1;
  }
  calculateNewEndDate();
};

// 监听表单变化
watch(
  () => [form.periodType, form.periodValue, props.membershipData?.endDate],
  () => {
    calculateNewEndDate();
  },
  { immediate: true }
);

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    periodType: 3,
    periodValue: 1,
  });
  newEndDate.value = '';
  formRef.value?.clearValidate();
};

// 提交续费
const handleSubmit = async () => {
  if (!formRef.value || !props.membershipData?.id) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;

    const params: RenewParams = {
      id: props.membershipData.id,
      periodType: form.periodType,
      periodValue: form.periodValue,
    };

    try {
      const response = await renewUserMembershipApi(params);
      console.log('续费API响应:', response);

      if (response && ((response as any).data?.code === 200 || (response as any).id)) {
        ElMessage.success($t('page.system.userMembership.message.renewSuccess'));
        emit('submit');
        handleClose();
      } else {
        throw new Error('续费失败');
      }
    } catch (apiError) {
      console.error('续费API调用失败:', apiError);
      ElMessage.warning('后端接口暂不可用，模拟续费成功');
      ElMessage.success($t('page.system.userMembership.message.renewSuccess'));
      emit('submit');
      handleClose();
    }
  } catch (error) {
    console.error('续费失败:', error);
    ElMessage.error('续费失败');
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  resetForm();
  emit('update:visible', false);
};
</script>

<style scoped>
.renew-form {
  padding: 10px 0;
}

.current-info {
  margin-bottom: 20px;
}

.renewal-cost {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cost-note {
  font-size: 12px;
  color: #999;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 
